/*
 * Copyright Copyright 2014 Takuya Asano
 * Copyright 2010-2014 Atilika Inc. and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// require vue as MVVM framework
// require kuromoji

var DIC_URL = "kuromoji/dict/";
const LYRIC_PATH = "/lyrics_data/";

var tokenizer = null;
// var lattice;  // Very large object. Unwatch this object from Model.
// var renderer = new dagreD3.Renderer();

const vm = new Vue({
    el: "#demo",
    data: {
        inputText: "",
        tokens: [],
        isLoading: true,
        message: "Loading dictionaries ...",
        svgStyle: "hidden",
        converHTML: ""
        
    },
    methods: {
        mounted() {
            this.getLyrics("未来へ");
        },
        tokenize: function () {
            console.log(tokenizer);
            if (this.inputText == "" || tokenizer == null) {
                this.tokens = [];
                // lattice = null;
                return;
            }
            try {
                // lattice = tokenizer.getLattice(vm.inputText);
                this.tokens = tokenizer.tokenize(this.inputText);
                // 将结果转为标注标签
                this.renderTag();
            } catch (e) {
                console.log(e);
                // lattice = null;
                this.tokens = [];
            }
        },

        // 片假名转平假名
        katakanaToHiragana: function (text) {
            if (!text) return "";
            return text.replace(/[\u30a1-\u30f6]/g, function (match) {
                var chr = match.charCodeAt(0) - 0x60;
                return String.fromCharCode(chr);
            });
        },

        // 
        renderTag: function (data) {
            if (!this.tokens) return;

            let html = '';
            // 遍历分词结果
            for (const token of this.tokens) {
                if (this.hasKanji(token.surface_form)) {
                    // 包含汉字的场合，拼接ruby注音标签
                    html += `<ruby class="ruby">${token.surface_form}<rt>${this.katakanaToHiragana(token.pronunciation)}</rt></ruby>`;
                } else {
                    // 不包含汉字，直接显示
                    html += token.surface_form;
                }
                console.log(html);
            }
            this.converHTML = html;
        },

        // 
        hasKanji: function (str) {
            const codePoints = [...str].map(c => c.codePointAt(0)); 
            return codePoints.some(cp  => 
              (cp >= 0x4E00 && cp <= 0x9FFF) || 
              (cp >= 0x3400 && cp <= 0x4DBF) ||
              (cp >= 0xF900 && cp <= 0xFAFF) ||
              (cp >= 0x20000 && cp <= 0x2A6DF)
            );
        },

        // 获取歌词文件
        getLyrics: function (filename) {
            const requestPath = `${LYRIC_PATH}${filename}.json`;
            fetch(requestPath)
                .then(response => response.json())
                .then(data => this.renderTag(data))
                .catch(error => console.log(error));
        }
    }
});


// フォームの内容が変化したらtokenizeする
vm.$watch("inputText", function (value) {
    // vm.graphEnabled = false;
    this.svgStyle = "hidden";
    this.tokenize();
});


// Load and prepare tokenizer
kuromoji.builder({ dicPath: DIC_URL }).build(function (error, _tokenizer) {
    if (error != null) {
        console.log(error);
    }
    tokenizer = _tokenizer;
    this.isLoading = false;
});


